package com.ddwl.wallet.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.*;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.SpringBeanUtil;
import com.ddwl.schema.vo.order.OrderInfoVo;
import com.ddwl.schema.vo.wallet.DistOrderInfoVo;
import com.ddwl.wallet.dao.DistOrderInfoDao;
import com.ddwl.wallet.dao.model.DistOrder;
import com.ddwl.wallet.dao.model.DistOrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

import static com.ddwl.common.constant.OrderEnum.OrderStatus.RECEIVED;
import static com.ddwl.common.constant.OrderEnum.OrderStatus.REFUND;

@Slf4j
@Service
public class DistOrderInfoService {


    @Resource
    private DistOrderInfoDao distOrderInfoDao;

    @Resource
    private DistOrderService distOrderService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 同步系统订单消息
     * @param orderInfoStr
     * @return
     */
    public DistOrderInfoVo syncInfo(String orderInfoStr){
        OrderInfoVo orderInfovo = JSON.parseObject(orderInfoStr,OrderInfoVo.class);
        DistOrderInfo orderInfo = distOrderInfoDao.queryDistOrderByOrderId(orderInfovo.getId());
        //如果订单不存在新增订单
        if (orderInfo == null) {
            //创建主订单
            orderInfo = createDistOrder(orderInfovo);
            //创建佣金明细订单
            List<DistOrder> orderList = createDist(orderInfo, orderInfovo.getCharityFlag());
            //如果是代理商品订单，需要按照代理等级进行分润
            if (BaseEnum.StatusEnum.ENABLE.getCode().equals(orderInfovo.getAgentFlag())) {
                orderList.addAll(createAgentOrder(orderInfo));
            }
            //根据创建的佣金信息包装主订单信息,分销员，区域合伙人等信息
            warpDistOrderInfo(orderInfo, orderList);
            distOrderInfoDao.insert(orderInfo);
        } else {
            //如果订单状态为已发货或者已退款更新订单状态
            if ((RECEIVED.getCode().intValue() == orderInfovo.getStatus() || REFUND.getCode().intValue() == orderInfovo.getStatus())
                    && DistConstant.DistOrderStatus.PAY.getCode().equals(orderInfo.getOrderStatus())) {
                distOrderInfoDao.confirmOrder(orderInfovo.getId(), orderInfovo.getConfirmTime());
                distOrderService.confirmOrder(orderInfovo.getId(), orderInfovo.getConfirmTime());
            }
        }
        //同步完订单之后做的事情
        syncAfter(orderInfo.getOrderId());
        return BeanConverUtils.convertBean(orderInfo,DistOrderInfoVo.class);
    }

    private void syncAfter(String orderId) {
        DistOrderInfo orderInfo = distOrderInfoDao.queryDistOrderByOrderId(orderId);
        if(DistConstant.DistOrderStatus.TAKE.getCode().equals(orderInfo.getOrderStatus())){
            //如果是商户订单用户确认收货直接结算
            if (GoodsEnum.CategoryTypeEnum.RETAIL.getCode().equals(orderInfo.getPlatformTag()) && !BaseEnum.ApplyEnum.SUCCEED.getCode().equals(orderInfo.getShopSettlementStatus().toString())) {
                rabbitTemplate.convertAndSend(RabbitMqConstants.DIST_SHOP_ORDER_SETTLEMENT_AMOUNT_QUEUE, orderInfo.getOrderId());
            }
            //开通门店订单佣金也直接结算
            if (DistConstant.DistrConfigType.SHOP.getCode().equals(orderInfo.getType())
                    || DistConstant.DistrConfigType.AGENT.getCode().equals(orderInfo.getType())) {
                rabbitTemplate.convertAndSend(RabbitMqConstants.DIST_DIST_ORDER_SETTLEMENT_AMOUNT_QUEUE, orderInfo.getOrderId());
            }
        }
    }

    private List<DistOrder> createAgentOrder(DistOrderInfo orderInfo) {
        return distOrderService.saveAgentOrderList(orderInfo);
    }

    /**
     * 生成订单佣金
     */
    private List<DistOrder> createDist(DistOrderInfo orderInfo,Integer charityFlag){
        //创建分佣
        List<DistOrder> distOrders = distOrderService.saveDistOrderList(orderInfo,charityFlag);
        //如果是商户订单生成商户佣金
        if (StringUtils.hasText(orderInfo.getShopId()) && GoodsEnum.CategoryTypeEnum.RETAIL.getCode().equals(orderInfo.getPlatformTag())) {
            distOrders.add(distOrderService.createShopDist(orderInfo));
        }
        //更新用户统计信息
        if(!CollectionUtils.isEmpty(distOrders)){
            SpringBeanUtil.getBean(DistOrderService.class).updateUserDist(distOrders);
        }
        return distOrders;
    }

    /**
     * 根据佣金信息包装主订单佣金信息
     * @param orderInfo
     * @param distOrders
     */
    private void warpDistOrderInfo(DistOrderInfo orderInfo, List<DistOrder> distOrders) {
        //如果没有生成佣金信息佣金状态默认改成结算完成
        if(CollectionUtils.isEmpty(distOrders)){
            orderInfo.setSettlementStatus(BaseEnum.ApplyEnum.SUCCEED.getCode());
            orderInfo.setClearingTime(Instant.now());
            return;
        }
        orderInfo.setTradeAmount(distOrders.stream().filter(distOrder -> !DistTypeEnum.SHOP.getType().equals(distOrder.getDistType())).map(DistOrder::getDistAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        DistOrder regionDist = distOrders.stream().filter(distOrder -> DistTypeEnum.REGION.getType().equals(distOrder.getDistType())).findFirst().orElse(null);

        DistOrder userDist = distOrders.stream().filter(distOrder -> DistTypeEnum.PERSONAL.getType().equals(distOrder.getDistType())).findFirst().orElse(null);
        BigDecimal agentAmount = distOrders.stream()
                .filter(distOrder -> null != distOrder.getDistAmount() && (DistTypeEnum.PERSONAL_AGENT_PROFIT.getType().equals(distOrder.getDistType())
                        || DistTypeEnum.STORE_AGENT_PROFIT.getType().equals(distOrder.getDistType())
                        || DistTypeEnum.ZONE_AGENT_PROFIT.getType().equals(distOrder.getDistType())))
                .map(distOrder -> distOrder.getDistAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderInfo.setAgentAmount(agentAmount);
        //保存区域佣金信息
        if (regionDist != null) {
            orderInfo.setRegionUserId(regionDist.getDistUserId());
            orderInfo.setRegionAmount(regionDist.getDistAmount());
        }
        //保存个人佣金信息
        if (userDist != null) {
            orderInfo.setDistUserId(userDist.getDistUserId());
            orderInfo.setDistAmount(userDist.getDistAmount());
        }
    }

    private DistOrderInfo createDistOrder(OrderInfoVo vo){
        if (null == vo.getDistType()) {
            vo.setDistType(DistConstant.DistrConfigType.PRODUCT.getCode());
        }
        if (DistConstant.DistrConfigType.SHOP.getCode().equals(vo.getDistType())) {
            //补全开店信息
            vo.setStatus(RECEIVED.getCode());
            vo.setConfirmTime(vo.getGmtCreated());
            vo.setPlatformTag(GoodsEnum.CategoryTypeEnum.PLATFORM.getCode());
        }
        DistOrderInfo order = new DistOrderInfo();
        order.setOrderUserId(vo.getUserId());
        order.setOrderId(vo.getId());
        order.setOrderPrice(vo.getPayAmount());
        order.setSource(vo.getSource());
        order.setOrderSpu(vo.getSkuSnapshoot());
        order.setPlatformTag(vo.getPlatformTag());
        order.setMchId(vo.getMchId());
        order.setOrderType(vo.getOrderType());
        order.setPayTime(vo.getPayTime());
        order.setOrderRegion(vo.getRegionId());
        if (RECEIVED.getCode().equals(vo.getStatus())) {
            order.setOrderStatus(DistConstant.DistOrderStatus.TAKE.getCode());
        } else {
            order.setOrderStatus(DistConstant.DistOrderStatus.PAY.getCode());
        }
        order.setConfirmTime(vo.getConfirmTime());
        order.setShopId(vo.getShopId());
        order.setNumberRefund(0);
        order.setShopSettlementStatus(0);
        order.setSettlementStatus(0);
        order.setType(vo.getDistType());
        return order;
    }
}
